<?php

namespace app\pub\controller;
use app\base\Auth;
use app\base\model\User;
use think\Controller;
use think\Loader;
use think\Request;

class index extends Controller
{
    /***
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function Login()
    {
        if (Request::instance()->isGet()) {
            return $this->fetch();
        }
        if (Request::instance()->isAjax()) {
            $data = Request::instance()->param();
            $validate = Loader::validate('PubValidate');
            if (!$validate->scene('login')->check($data)) {
                return ['code'=>-1,'msg'=>$validate->getError()];
            }
            $user = User::get(['username' => $data['user_name']]);
            if (is_null($user)) {
                return ['code'=>-1,'msg'=>'账号不存在'];
            }
            if (md5($data['user_pwd'])!=$user->password) {
                return ['code'=>-1,'msg'=>'密码错误'];
            }
            $remember=isset($data['remember'])?true:false;
            Auth::doLogin($user->toArray(),$remember);
            return ['code' => 1, 'msg' => '登录成功','url'=>'/index'];
        }
    }



    public function register()
    {
        if (Request::instance()->isGet()) {
            return $this->fetch();
        }
        if (Request::instance()->isAjax()) {
            $data = Request::instance()->param();
            $validate = Loader::validate('PubValidate');
            if (!$validate->check($data)) {
                return ['code'=>-1,'msg'=>$validate->getError()];
            }
            if ($data['user_pwd']!=$data['user_rpwd']) {
                return ['code'=>-1,'msg'=>'两次账号密码输入不一致'];
            }


            $user = User::get(['username' => $data['user_name']]);
            if (!is_null($user)) {
                return ['code'=>-1,'msg'=>'账号已存在'];
            }
            User::create([
                'username' => $data['user_name'],
                'password' => md5($data['user_pwd']),
                'usernick' => $data['user_nick'],
                'userstat' => 2,

            ]);
            return ['code'=>1,'msg'=>'注册成功'];



        }
    }




    public function loginOut()
    {
        Auth::outLogin();
        $this->success('退出成功', '/index');
    }
}